<!-- 用户管理-新增/编辑/查看用户的具体信息 -->
<template>
  <div class="layout-warpper user-info-page">
    <div v-loading="pageLoading" class="layout-body">
      <div class="user-info-body">
        <el-form
          ref="userForm"
          grid
          :model="userForm"
          label-width="135px"
          class="ui-ml10 ui-mr10"
          :rules="userRules"
          :disabled="operationType === 'view' || haveSaved"
        >
          <el-collapse v-model="activeNames" icon-text card>
            <el-collapse-item title="基本信息" name="1">
              <!-- 人员编码由后端返回，前端不需要填写 -->
              <el-form-item :span="12" label="人员编码" prop="userCode">
                <el-input v-model="userForm.userCode" disabled />
              </el-form-item>
              <el-form-item :span="12" label="用户姓名" prop="userName">
                <el-input v-model="userForm.userName" placeholder="请输入" maxlength="100" autocomplete="off" />
              </el-form-item>
              <el-form-item :span="12" label="身份证号" prop="userIdCard">
                <el-input v-model="userForm.userIdCard" placeholder="请输入" />
              </el-form-item>
              <el-form-item :span="12" label="联系电话" prop="userTel">
                <el-input v-model="userForm.userTel" placeholder="请输入" />
              </el-form-item>
              <el-form-item :span="12" label="用户状态" prop="userStatus">
                <el-radio-group v-model="userForm.userStatus">
                  <el-radio v-for="item in userStatusRadios" :key="item.value" :label="item.value">
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="账号信息" name="2">
              <el-form-item :span="12" label="登录名" prop="loginName">
                <el-input v-model="userForm.loginName" placeholder="请输入" maxlength="100" />
              </el-form-item>
              <!-- 编辑和查看的时候都不显示密码 -->
              <el-form-item v-if="operationType === 'new'" :span="12" label="密码" prop="password">
                <el-input
                  v-model="userForm.password"
                  placeholder="请输入"
                  show-password
                  autocomplete="new-password"
                  @blur="getPwdStrength(userForm.password)"
                />
              </el-form-item>
            </el-collapse-item>
            <!-- {{ userForm.userRoles }}
            {{ userRoleCheckboxs }} -->
            <!-- {{ operationType }} view
            {{ userForm.userRoles }} -->
            <el-collapse-item title="角色信息" name="3">
              <el-form-item :span="12" label="选择角色" prop="userRoles">
                <el-checkbox-group disabled v-if="operationType === 'view'" v-model="userForm.userRoles">
                  <template v-for="item in userInitData.roleList">
                    <el-checkbox
                      v-if="userForm.userRoles.indexOf(item.value) > -1"
                      :key="item.value"
                      :label="item.value"
                    >
                      {{ item.label }}
                    </el-checkbox>
                  </template>
                </el-checkbox-group>
                <el-checkbox-group disabled v-else-if="operationType === 'edit'" v-model="userForm.userRoles">
                  <template v-for="item in userInitData.roleList">
                    <el-checkbox
                      v-if="userForm.userRoles.indexOf(item.value) > -1"
                      :key="item.value"
                      :label="item.value"
                    >
                      {{ item.label }}
                    </el-checkbox>
                  </template>
                </el-checkbox-group>
                <el-checkbox-group v-else v-model="userForm.userRoles">
                  <el-checkbox v-for="item in userRoleCheckboxs" :key="item.value" :label="item.value">
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <!-- 配置见证人员权限的div块 -->
              <div v-if="userForm.userRoles.indexOf('GDW_R_WITNESS_PERSON') > -1" class="el-col el-col-24">
                <div class="ui-title">配置见证人员权限</div>
                <el-button
                  v-if="operationType !== 'view'"
                  type="primary"
                  icon="icon-xinzengsvg1"
                  size="medium"
                  @click="addRights('jzy')"
                >
                  新增见证人员权限
                </el-button>
                <!-- {{ userForm.jzyRights }} -->
                <el-table
                  :data="userForm.jzyRights"
                  highlight-current-row
                  style="width: 100%"
                  card
                  default-expand-all
                  :show-header="false"
                >
                  <el-table-column type="expand" width="25">
                    <template slot-scope="scope">
                      <el-table
                        :data="scope.row.children"
                        isdrag
                        style="width: 100%"
                        :no-hover="true"
                        class="table-in-table"
                      >
                        <el-table-column type="index" label="序号" width="65" align="center" />
                        <!-- <el-table-column prop="secondLevelIndustry" label="行业" min-width="150">
                          <template slot-scope="cScope">
                            {{ secondLevelIndustrysObj[cScope.row.firstLevelIndustry][cScope.row.secondLevelIndustry] }}
                          </template>
                        </el-table-column> -->
                        <el-table-column
                          prop="secondLevelIndustry"
                          label="行业"
                          min-width="150"
                          :formatter="secondLevelIndustryFormatter"
                        ></el-table-column>
                        <el-table-column
                          prop="tradeType"
                          label="交易方式"
                          min-width="300"
                          :formatter="tradTypeFormatter"
                        ></el-table-column>
                        <el-table-column
                          prop="witnessLink"
                          label="见证环节"
                          min-width="300"
                          :formatter="witnessLinkFormatter"
                        />
                        <el-table-column label="操作" v-if="operationType !== 'view'" min-width="100">
                          <template slot-scope="cScope">
                            <el-button type="text" @click="editJzyRights(cScope.row, cScope.$index)">编辑</el-button>
                            <el-button
                              type="text"
                              @click="delRights(cScope.row, cScope.$index, 'jzy', 'second', scope.$index)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </el-table-column>
                  <el-table-column type="index" width="40" />
                  <el-table-column prop="firstLevelIndustry" min-width="700">
                    <template slot-scope="scope">
                      <!-- <span style="font-weight: bold">{{ firstLevelIndustrysObj[scope.row.firstLevelIndustry] }}</span> -->
                      <span style="font-weight: bold">{{ firstLevelIndustrysObj[scope.row.firstLevelIndustry] }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" v-if="operationType !== 'view'" width="60">
                    <template slot-scope="scope">
                      <el-button type="text" @click="delRights(scope.row, scope.$index, 'jzy', 'first')">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <!-- 配置见证管理员权限的div块 -->
              <div v-if="userForm.userRoles.indexOf('GDW_R_WITNESS_MANAGER') > -1" class="el-col el-col-24">
                <div class="ui-title">配置见证管理员权限</div>
                <el-button
                  v-if="operationType !== 'view'"
                  type="primary"
                  icon="icon-xinzengsvg1"
                  size="medium"
                  @click="addRights('jzgly')"
                >
                  新增见证管理员权限
                </el-button>
                <!-- {{ userForm.jzglyRights }} -->
                <el-table
                  :data="userForm.jzglyRights"
                  highlight-current-row
                  style="width: 100%"
                  card
                  default-expand-all
                  :show-header="false"
                >
                  <el-table-column type="expand" width="25">
                    <template slot-scope="scope">
                      <el-table
                        :data="scope.row.children"
                        isdrag
                        style="width: 100%"
                        :no-hover="true"
                        class="table-in-table"
                      >
                        <el-table-column type="index" label="序号" width="65" align="center" />
                        <el-table-column
                          prop="secondLevelIndustry"
                          label="行业"
                          min-width="150"
                          :formatter="secondLevelIndustryFormatter"
                        ></el-table-column>
                        <!-- <el-table-column prop="tradeType" label="交易方式" min-width="300">
                          <template slot-scope="cScope">
                            {{ tradeTypesObj[cScope.row.firstLevelIndustry][cScope.row.tradeType] }}
                          </template>
                        </el-table-column> -->
                        <el-table-column
                          prop="tradeType"
                          label="交易方式"
                          min-width="300"
                          :formatter="tradTypeFormatter"
                        ></el-table-column>
                        <el-table-column
                          prop="witnessLink"
                          label="见证环节"
                          min-width="300"
                          :formatter="witnessLinkFormatter"
                        />
                        <el-table-column label="操作" v-if="operationType !== 'view'" min-width="100">
                          <template slot-scope="cScope">
                            <el-button type="text" @click="editJzyRights(cScope.row, cScope.$index, 'jzgly')">
                              编辑
                            </el-button>
                            <el-button
                              type="text"
                              @click="delRights(cScope.row, cScope.$index, 'jzgly', 'second', scope.$index)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </el-table-column>
                  <el-table-column type="index" width="40" />
                  <el-table-column prop="firstLevelIndustry" min-width="700">
                    <template slot-scope="scope">
                      <span style="font-weight: bold">{{ firstLevelIndustrysObj[scope.row.firstLevelIndustry] }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" v-if="operationType !== 'view'" width="60">
                    <template slot-scope="scope">
                      <el-button type="text" @click="delRights(scope.row, scope.$index, 'jzgly', 'first')">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form>
      </div>
    </div>
    <div v-if="operationType !== 'view' && !haveSaved" class="layout-footer user-info-footer">
      <el-button type="primary" :loading="saveLoading" @click="saveUserInfo(userForm)">保存</el-button>
    </div>
    <!-- 新增、编辑见证人权限的弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      draggable
      width="450px"
      :title="rightsDialogTitle"
      :visible.sync="rightsDialogShow"
      custom-class="dialog-middle"
      @close="cancel"
    >
      <!-- 您当前已没有此业务权限，请先确认该见证人已无此权限的业务，以免对已有业务造成影响，明确后可进行删除相应权限操作 -->
      <el-form ref="rightsForm" :model="rightsForm" label-width="80px" :rules="rightsRules">
        <el-form-item label="行业类别" prop="industryType">
          <el-cascader
            v-model="rightsForm.industryType"
            class="ui-w"
            placeholder="请选择"
            :options="industryTypeOptions"
            :props="{ multiple: true }"
            collapse-tags
            :collapse-tags-max-num="1"
            popper-class="select-border-circle"
            :disabled="rightsDialogType === 'edit'"
            @change="industryTypeChange"
          />
        </el-form-item>
        <!-- {{ [selectedFirstLevelIndustry] }} -->
        <!-- {{ tenderModeOptionsObj }} -->
        <!-- {{ tenderModeOptionsArr }} -->
        <el-form-item label="交易方式" prop="tradeType">
          <!-- <el-select
            v-model="rightsForm.tradeType"
            class="ui-w"
            placeholder="请选择"
            @change="tradeTypeChange"
            :disabled="rightsForm.industryType.length === 0 || rightsDialogType === 'edit'"
          >
            <el-option
              v-for="item in tradeTypesOptionsObj[selectedFirstLevelIndustry]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select> -->
          <el-select
            v-model="rightsForm.tradeType"
            class="ui-w"
            :disabled="rightsForm.industryType.length === 0 || rightsDialogType === 'edit'"
            placeholder="请选择"
            @change="tenderModeFn"
          >
            <!-- <el-option v-for="(label, key) in tenderModeOptionsObj" :key="key" :label="label" :value="key" /> -->
            <el-option
              v-for="(item, index) in tenderModeOptionsArr"
              :key="item.value + index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <!--  v-if="rightsRole === 'jzy'" -->
        <!-- {{ rightsForm.witnessLink }} -->
        <el-form-item label="见证环节" prop="witnessLink">
          <!-- <el-select
            v-model="rightsForm.witnessLink"
            class="ui-w"
            @change="changeWitnessLinkFn"
            placeholder="请选择"
            multiple
            collapse-tags
            :disabled="rightsForm.industryType.length === 0 || rightsForm.tradeType === ''"
          >
            <el-option
              v-for="item in witnessLinksOptionsObj[selectedFirstLevelIndustry + '-' + rightsForm.tradeType]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select> -->
          <!-- {{ witnessLink }} -->
          <!-- {{ witnessLinkOptionsObj }} -->
          <el-select
            v-model="rightsForm.witnessLink"
            class="ui-w"
            @change="changeWitnessLinkFn"
            placeholder="请选择"
            multiple
            collapse-tags
            :disabled="rightsForm.industryType.length === 0 || rightsForm.tradeType === ''"
          >
            <template v-for="(item, index) in witnessLink">
              <template v-if="witnessLinkOptionsObj[item.value]">
                <!-- <el-option v-for="(label, key) in witnessLinkOptionsObj" :key="key" :label="label" :value="key" /> -->
                <el-option
                  :disabled="item.disabled"
                  :key="index"
                  :label="witnessLinkOptionsObj[item.value]"
                  :value="item.value"
                />
              </template>
            </template>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--  && rightsRole === 'jzy' -->
        <el-button
          type="primary"
          :disabled="
            rightsForm.industryType.length === 0 || rightsForm.tradeType === '' || rightsForm.witnessLink.length === 0
          "
          :loading="submitLoading"
          @click="saveUserRights()"
        >
          确定
        </el-button>
        <el-button type="primary" @click="cancel()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  import { userAdd, userUpdate, userDetail } from "../../../../api/api";
  export default {
    // 引入组件
    components: {},
    props: {
      // 用户状态选择项
      userInitData: {
        type: Object,
        default: () => {}
      },
      // 用户状态选择项
      userStatusRadios: {
        type: Array,
        default: () => [],
        required: true
      },
      // 用户角色选择项
      userRoleCheckboxs: {
        type: Array,
        default: () => [],
        required: true
      },
      roleList: {
        type: Array,
        default: () => [],
        required: true
      },
      // 行业类别选择项
      industryTypeOptions: {
        type: Array,
        default: () => [],
        required: true
      },
      // 行业类型+交易方式+见证环节之间的关联数组
      industryTypeAndTenderModeArr: {
        type: Array,
        default: () => []
        // required: true
      },
      industryTypes: {
        type: Array,
        default: () => [],
        required: true
      },
      industryAll: {
        type: Array,
        default: () => [],
        required: true
      },
      witnessLink: {
        type: Array,
        default: () => [],
        required: true
      },
      tenderModes: {
        type: Array,
        default: () => [],
        required: true
      },
      // 操作类型，new(新增)，edit(编辑)，view(查看)
      operationType: {
        type: String,
        default: ""
      },
      // 用户编辑和查看的数据id
      witnessUserId: {
        type: String,
        default: ""
      }
    },
    // eslint-disable-next-line max-lines-per-function
    data() {
      // 择行业类别多选，交易方式取行业交集
      const checkIndustryType = (rule, value, callback) => {
        // if (!value) {
        //   callback(new Error("请选择行业类别!"));
        // }
        setTimeout(() => {
          // console.log("1111111111111");
          // console.log("rule", rule);
          // console.log("value", value);
          if (value.length && !Object.keys(this.tenderModeOptionsObj).length) {
            callback(new Error("您选择的行业类别存在交易方式权限冲突，请重新选择"));
          } else {
            callback();
          }
        }, 500);
      };
      // 身份证号的验证
      const checkIDCard = (rule, value, callback) => {
        if (this.$cafeUtils.isIDCard(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的身份证号"));
        }
      };
      // 联系电话的验证
      const checkTelphone = (rule, value, callback) => {
        if (!value || this.$cafeUtils.isPhone(value) || this.$cafeUtils.isTel(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的联系电话"));
        }
      };
      // 密码的验证
      const checkPassWord = (rule, value, callback) => {
        // 纯数字：
        const a = /^\d+$/;
        // 纯字母：
        const b = /^[a-zA-Z]+$/;
        // 纯特殊字符：
        const c = /^[~!@#$%^&]+$/;
        if (a.test(value) || b.test(value) || c.test(value)) {
          callback(new Error("密码强度过低！"));
        } else {
          callback();
        }
      };
      // 这里存放数据
      return {
        submitLoading: false, //
        activeNames: ["1", "2", "3"], // 折叠面板默认全部展开
        tenderModeOptionsArr: [], // 新加入，与tenderModeOptionsObj配合使用
        tenderModeOptionsObj: {},
        witnessLinkOptionsObj: {},
        witnessLinkOptionsArr: [],
        userForm: {
          userCode: "",
          userName: "",
          userIdCard: "",
          userTel: "",
          userStatus: "ENABLE", // 用户状态默认开启
          loginName: "",
          password: "",
          userRoles: [],
          jzyRights: [], // 见证员权限，一级数组以行业类别的一级菜单保存，二级菜单是选择的其它值
          jzglyRights: [] // 见证管理员权限，一级数组以行业类别的一级菜单保存，二级菜单是选择的其它值
        },
        userRules: {
          userName: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],
          userIdCard: [
            { required: true, message: "请输入身份证号", trigger: "blur" },
            { validator: checkIDCard, trigger: "blur" }
          ],
          userTel: [{ validator: checkTelphone, trigger: "blur" }],
          loginName: [{ required: true, message: "请输入登录名", trigger: "blur" }],
          password: [
            { required: true, message: "请输入8到16位长度的密码", trigger: "blur" },
            { min: 8, max: 16, message: "长度在 8 到 16 个字符", trigger: "blur" },
            { validator: checkPassWord, trigger: "blur" }
          ],
          userRoles: [{ required: true, message: "请选择角色", trigger: "change" }]
        },
        rightsDialogShow: false,
        rightsDialogTitle: "新增见证人员权限", // 权限弹窗标题
        rightsRole: "", // 角色，两类：jzy:见证员，jzgly:见证管理员
        rightsDialogType: "", // 弹窗操作类型，new(新增)，edit(编辑)
        rightsForm: {
          industryType: [], // 行业类别-二级下拉，一级菜单单选，二级菜单多选
          tradeType: "", // 交易方式
          witnessLink: [] // 见证环节
        },
        rightsRules: {
          industryType: [
            { required: true, message: "请选择行业类别", trigger: "change" },
            { validator: checkIndustryType, trigger: "change" }
          ],
          tradeType: [{ required: true, message: "请选择交易方式", trigger: "change" }],
          witnessLink: [{ required: true, message: "请选择见证环节", trigger: "change" }]
        },
        selectedFirstLevelIndustry: "", // 行业类别选择的一级行业的值
        tradeTypesObj: {}, // 依据一级行业分组显示的“交易方式”value-lable映射值
        tradeTypesOptionsObj: {}, // 依据一级行业分组显示的“交易方式”value,lable数组
        witnessLinksObj: {}, // 依据“一级行业-交易方式”分组的见证环节value-lable映射值
        witnessLinksOptionsObj: {}, // 依据“一级行业-交易方式”分组的“见证环节”value,lable数组
        firstLevelIndustrysObj: {}, // 一级行业value-lable映射值
        secondLevelIndustrysObj: {}, // 根据一级行业分组的二级行业value-lable映射值
        alreadySetTradeTypeObj: {}, // 已经设置过的“交易方式”，依据依据“一级行业-二级行业”分组显示
        saveLoading: false,
        pageLoading: false,
        haveSaved: false // 是否已经保存
      };
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {},
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.initOptionsObj();
      if (this.operationType === "edit" || this.operationType === "view") {
        this.userDetailFn(this.witnessUserId);
      }
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    // 生命周期 - 销毁之前
    beforeDestroy() {},
    // 生命周期 - 销毁完成
    destroyed() {},
    // 如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
    // 方法集合
    methods: {
      // 获取密码的强度
      getPwdStrength(pwd) {
        // //纯数字：
        // var a = /^\d+$/;
        // //纯字母：
        // var b = /^[a-zA-Z]+$/;
        // //纯特殊字符：
        // var c = /^[~!@#$%^&]+$/;
        // 字母+数字：
        const d = /^(?!\d+$)(?![a-zA-Z]+$)[a-zA-Z\d]+$/;
        // 字母+特殊字符：
        const f = /^(?![a-zA-Z]+$)(?![~!@#$%^&]+$)[a-zA-Z~!@#$%^&]+$/;
        // 数字+特殊字符：
        const g = /^(?!\d+)(?![~!@#$%^&]+$)[\d~!@#$%^&]+$/;
        // 字母+数字+特殊字符：
        const r = /^(?!\d+$)(?![a-zA-Z]+$)(?![~!@#$%^&]+$)[\da-zA-Z~!@#$%^&]+$/;
        if (pwd && pwd.length >= 8 && pwd.length <= 16) {
          if (d.test(pwd) || f.test(pwd) || g.test(pwd)) {
            this.$message({
              message: "密码强度：中",
              single: true,
              type: "success"
            });
          } else if (r.test(pwd)) {
            this.$message({
              message: "密码强度：强",
              single: true,
              type: "success"
            });
          }
        }
      },
      // 获取交易方式、见证环节、一级行业、二级行业的value-lable映射值
      initOptionsObj() {
        this.tenderModeOptionsObj;
        this.tenderModes; // 所有交易方式
        this.witnessLink;
        // this.tenderModeOptionsObj = JSON.parse(JSON.stringify(this.tenderModes));
        // this.witnessLinkOptionsObj = JSON.parse(JSON.stringify(this.witnessLink));
        this.tenderModes.forEach((itemD) => {
          this.tenderModeOptionsObj[itemD.value] = itemD.label;
        });
        this.tenderModeOptionsArr = this.tenderModes; // 编辑用
        // 这里不是编辑弹框初始化
        // this.witnessLink.forEach((itemD) => {
        //   this.witnessLinkOptionsObj[itemD.value] = itemD.label;
        // });
        // this.rightsForm = {
        //   index: index,
        //   industryType: [[item.firstLevelIndustry, item.secondLevelIndustry]],
        //   tradeType: item.tradeType,
        //   witnessLink: currWitnessLink
        // };
        // debugger
        for (let i = 0; i < this.industryTypeAndTenderModeArr.length; i++) {
          const ei = this.industryTypeAndTenderModeArr[i];
          if (ei.children) {
            this.tradeTypesObj[ei.value] = {};
            this.tradeTypesOptionsObj[ei.value] = [];
            for (let j = 0; j < ei.children.length; j++) {
              const ej = ei.children[j];
              this.tradeTypesObj[ei.value][ej.value] = ej.label;
              this.tradeTypesOptionsObj[ei.value].push({
                value: ej.value,
                label: ej.label
              });
              if (ej.children) {
                const jkey = `${ei.value}-${ej.value}`;
                this.witnessLinksObj[jkey] = {};
                this.witnessLinksOptionsObj[jkey] = [];
                for (let k = 0; k < ej.children.length; k++) {
                  const ek = ej.children[k];
                  this.witnessLinksObj[jkey][ek.value] = ek.label;
                  this.witnessLinksOptionsObj[jkey].push({
                    value: ek.value,
                    label: ek.label
                  });
                }
              }
            }
          }
        }
        this.industryTypes.forEach((item) => {
          this.firstLevelIndustrysObj[item.value] = item.label;
        });
        // 获取行业映射值
        for (let i = 0; i < this.industryTypeOptions.length; i++) {
          const ei = this.industryTypeOptions[i];
          // this.firstLevelIndustrysObj[ei.value] = ei.label;
          this.secondLevelIndustrysObj[ei.value] = {};
          if (ei.children) {
            for (let j = 0; j < ei.children.length; j++) {
              const ej = ei.children[j];
              this.secondLevelIndustrysObj[ei.value][ej.value] = ej.label;
            }
          }
        }
      },
      // 新增用户权限, role包含两类参数：jzy:见证员，jzgly:见证管理员
      addRights(role) {
        this.rightsRole = role;
        if (this.rightsRole === "jzy") {
          this.rightsDialogTitle = "新增见证人员权限";
          this.industryTypeOptionDisabled(this.userForm.jzyRights);
        } else {
          this.rightsDialogTitle = "新增见证管理员权限";
          this.industryTypeOptionDisabled(this.userForm.jzglyRights);
        }
        this.rightsForm = {
          industryType: [], // 行业类别-二级下拉，一级菜单单选，二级菜单多选
          tradeType: "", // 交易方式
          witnessLink: [] // 见证环节
        };
        this.selectedFirstLevelIndustry = "";
        this.rightsDialogType = "new";
        this.rightsDialogShow = true;
        if (this.$refs.rightsForm) {
          this.$nextTick(() => {
            this.$refs.rightsForm.clearValidate();
          });
        }
      },
      // 依据条件禁用“行业类别”的下拉选项
      industryTypeOptionDisabled(rightsArr) {
        console.log("rightsArr", rightsArr);
        // 1. 首先，获取一级行业下的每个二级行业都配置了哪些权限
        const aObj = {};
        for (let i = 0; i < rightsArr.length; i++) {
          const ei = rightsArr[i];
          if (ei.children) {
            aObj[ei.firstLevelIndustry] = {};
            for (let j = 0; j < ei.children.length; j++) {
              const ej = ei.children[j];
              if (!aObj[ei.firstLevelIndustry][ej.secondLevelIndustry]) {
                aObj[ei.firstLevelIndustry][ej.secondLevelIndustry] = [];
              }
              aObj[ei.firstLevelIndustry][ej.secondLevelIndustry].push(ej.tradeType);
            }
          }
        }
        this.alreadySetTradeTypeObj = aObj;
        console.log("aObj", aObj);
        setTimeout(() => {
          this.industryTypeOptions.forEach((itemA, i) => {
            this.$set(this.industryTypeOptions[i], "disabled", false);
            if (itemA.children && itemA.children.length > 0) {
              // console.log("itemA", itemA);
              let num = 0; // 记录二级菜单的禁用数量
              itemA.children.forEach((itemB) => {
                // console.log("itemB", itemB);
                // console.log("itemB.childrenIndustry", itemB.childrenIndustry);
                this.$set(itemB, "disabled", false);
                // console.log("aObj[itemA.value]", aObj[itemA.value]);
                if (
                  aObj[itemA.value] &&
                  aObj[itemA.value][itemB.value] &&
                  aObj[itemA.value][itemB.value].length === itemB.childrenIndustry.length
                ) {
                  // console.log("========", aObj[itemA.value][itemB.value]);
                  this.$set(itemB, "disabled", true);
                  // console.log("itemB-", itemB);
                  num++;
                }
              });
              if (itemA.children.length === num) {
                this.$set(itemA, "disabled", true);
              }
            } else {
              this.$set(itemA, "disabled", true);
            }
          });
          console.log("");
          // this.tenderModeOptionsArr = [];
        }, 300);
        // tenderModeOptionsObj;
        /* 2. 然后，依据上面的配置，禁用行业
        禁用逻辑：
          a. 遍历下拉选项数组，判断一级行业有没有包含二级行业，若包含，则默认不禁用，否则禁用
          b. 当包含二级行业时，继续遍历二级行业，当已设置中包含该一级和二级行业，且二级行业设置的数量与该一级行业下的交易方式数量相等，则认为二级行业已经被设置包含所有交易方式，即禁用。
          c. 当某个一级行业下所有的二级行业被禁用时，该一级行业也被禁用
      */
        for (let i = 0; i < this.industryTypeOptions.length; i++) {
          const ei = this.industryTypeOptions[i];
          if (ei.children && ei.children.length > 0) {
            this.$set(this.industryTypeOptions[i], "disabled", false);
            let num = 0; // 记录二级菜单的禁用数量
            for (let j = 0; j < ei.children.length; j++) {
              const ej = ei.children[j];
              this.$set(ej, "disabled", false);
              if (
                aObj.hasOwnProperty(ei.value) &&
                aObj[ei.value].hasOwnProperty(ej.value) &&
                aObj[ei.value][ej.value].length === this.tradeTypesOptionsObj[ei.value].length
              ) {
                this.$set(ej, "disabled", true);
                num++;
              }
            }
            if (ei.children.length === num) {
              this.$set(this.industryTypeOptions[i], "disabled", true);
            }
          } else {
            this.$set(this.industryTypeOptions[i], "disabled", true);
          }
        }
      },
      // 交易方式
      tenderModeFn(val) {
        console.log("tenderModeFn", val);
        // this.tenderModeOptionsObj = {};
        const industrySecondLevel = this.rightsForm.industryType.map((item) => item[1]);
        console.log("industrySecondLevel", industrySecondLevel);
        // const tempItemDObj = {};
        const tempItemEObj = {};
        let tempArr = [];
        let firstRunFlag = true;
        this.industryTypeOptions.forEach((itemA) => {
          // console.log("itemA", itemA);
          itemA.children.forEach((itemB) => {
            // console.log("itemB", itemB);
            if (industrySecondLevel.some((itemC) => itemC === itemB.value)) {
              console.log("1111", firstRunFlag);
              console.log("tenderModeFn-itemB.childrenIndustry", itemB.childrenIndustry);
              itemB.childrenIndustry.forEach((itemD) => {
                if (itemD.value === val) {
                  console.log("itemD", itemD);
                  if (firstRunFlag) {
                    tempArr = itemD.children;
                    firstRunFlag = false;
                  } else {
                    tempArr = tempArr.filter((itemF) => itemD.children.some((itemE) => itemE.value === itemF.value));
                  }
                  console.log("tenderModeFn-tempArr", tempArr);
                }
              });
            }
          });
        });
        console.log("tenderModeFn-tempArr", tempArr);
        if (tempArr.length) {
          tempArr.forEach((item) => {
            tempItemEObj[item.value] = item.label;
          });
        }
        // 您选择的行业类别存在交易方式权限冲突，请重新选择
        this.witnessLinkOptionsObj = JSON.parse(JSON.stringify(tempItemEObj));
        const linkArr = [];
        if (this.rightsForm.witnessLink.length) {
          console.log("this.rightsForm.witnessLink", this.rightsForm.witnessLink);
          this.rightsForm.witnessLink.forEach((item) => {
            if (this.witnessLinkOptionsObj[item]) {
              linkArr.push(item);
            }
          });
        }
        if (tempArr.length === 1) {
          this.$set(this.rightsForm, "witnessLink", [tempArr[0].value]);
          // this.rightsForm.witnessLink = tempArr[0].value;
        } else {
          this.rightsForm.witnessLink = linkArr;
        }
      },
      // 用户行业类型值发生变化
      // tradeTypeChange(val) {
      //   //   v-model="rightsForm.witnessLink"
      //   //   class="ui-w"
      //   //   @change="changeWitnessLinkFn"
      //   //   placeholder="请选择"
      //   //   multiple
      //   //   collapse-tags
      //   //   :disabled="rightsForm.industryType.length === 0 || rightsForm.tradeType === ''"
      //   // >
      //   //   <el-option
      //   //     v-for="item in witnessLinksOptionsObj[selectedFirstLevelIndustry + '-' + rightsForm.tradeType]"
      //   const arr = this.witnessLinksOptionsObj[`${this.selectedFirstLevelIndustry}-${this.rightsForm.tradeType}`];
      //   console.log("val", val);
      //   console.log("arr", arr);
      //   console.log("this.rightsForm.witnessLink;", this.rightsForm.witnessLink);
      //   this.rightsForm.witnessLink.forEach((item, index) => {
      //     if (arr.some((itemA) => itemA.value === item)) {
      //       this.rightsForm.witnessLink.splice(index, 1);
      //     }
      //   });
      // },
      formatIndustryFn() {
        // this.tenderModeOptionsObj = {};
        // 选中二级行业
        const industrySecondLevel = this.rightsForm.industryType.map((item) => item[1]);
        console.log("industrySecondLevel", industrySecondLevel);
        const tempItemDObj = {};
        // const tempItemEObj = {};
        let tempArr = [];
        let firstRunFlag = true;
        this.industryTypeOptions.forEach((itemA) => {
          console.log("itemA", itemA);
          itemA.children.forEach((itemB) => {
            console.log("itemB", itemB);
            if (industrySecondLevel.some((itemC) => itemC === itemB.value)) {
              if (firstRunFlag) {
                tempArr = itemB.childrenIndustry;
                firstRunFlag = false;
              } else {
                console.log("itemB.childrenIndustry", itemB.childrenIndustry);
                tempArr = JSON.parse(
                  JSON.stringify(
                    itemB.childrenIndustry.filter((itemD) => tempArr.some((itemE) => itemE.value === itemD.value))
                  )
                );
              }
            }
          });
        });
        // 交易方式，删除后初始化
        tempArr.forEach((itemG) => {
          this.$set(itemG, "disabled", false);
        });
        this.industryTypeOptions.forEach((itemA) => {
          console.log("itemA", itemA);
          itemA.children.forEach((itemB) => {
            console.log("itemB", itemB);
            if (industrySecondLevel.some((itemC) => itemC === itemB.value)) {
              if (this.alreadySetTradeTypeObj[itemA.value] && this.alreadySetTradeTypeObj[itemA.value][itemB.value]) {
                this.alreadySetTradeTypeObj[itemA.value][itemB.value].forEach((itemF) => {
                  console.log("itemF", itemF);
                  tempArr.forEach((itemG) => {
                    if (itemG.value === itemF) {
                      this.$set(itemG, "disabled", true);
                    }
                  });
                });
              }
            }
          });
        });
        console.log("tempArr", tempArr);
        if (tempArr.length) {
          tempArr.forEach((itemD) => {
            tempItemDObj[itemD.value] = itemD.label;
          });
        }
        // 您选择的行业类别存在交易方式权限冲突，请重新选择
        // this.zsTypeOptionsObj = JSON.parse(JSON.stringify(tempItemEObj));
        this.tenderModeOptionsObj = JSON.parse(JSON.stringify(tempItemDObj));
        this.tenderModeOptionsArr = tempArr;
        console.log("this.alreadySetTradeTypeObj", this.alreadySetTradeTypeObj);
        if (!this.tenderModeOptionsArr.some((item) => item.value === this.rightsForm.tradeType)) {
          if (this.tenderModeOptionsArr.length === 1) {
            this.rightsForm.tradeType = this.tenderModeOptionsArr[0].value;
          } else {
            this.rightsForm.tradeType = "";
          }
          this.rightsForm.witnessLink = [];
        }
        this.tenderModeFn(this.rightsForm.tradeType);
        // this.tenderModeOptionsArr.forEach((itemA) => {
        //   console.log("itemA", itemA);
        //   // rightsForm.tradeType
        //   // this.rightsForm.witnessLink
        //   // this.$set(itemA, "disabled", false);
        //   // if (this.rightsForm) {
        //   // }
        //   // this.$set(itemA, "disabled", true);
        // });
      },
      industryTypeChange(val) {
        console.log("val", val);
        console.log("rightsForm.industryType", this.rightsForm.industryType);
        if (val.length === 0) {
          // 行业类别的值发生变化，清空交易方式和见证环节的值
          this.rightsForm.tradeType = "";
          this.rightsForm.witnessLink = [];
          return;
        }
        setTimeout(() => {
          this.formatIndustryFn(val);
        }, 100);
        // rightsForm.witnessLink
        // 还有禁用的逻辑没有加
        // 若之前选择过行业类别，且现在选择的一级菜单有和之前不一样的，去掉这些值；若之前没有选择过，记录一下最新的选择
        if (this.selectedFirstLevelIndustry !== "") {
          const newArr = [];
          for (let i = 0; i < val.length; i++) {
            if (val[i][0] !== this.selectedFirstLevelIndustry) {
              newArr.push(val[i]);
            }
          }
          // 判断一下有没有更换一级菜单
          if (newArr.length > 0) {
            this.rightsForm.industryType = newArr;
            this.selectedFirstLevelIndustry = newArr[0][0]; // 记录一下最新选择的行业类别的一级菜单
            // 行业类别的值发生变化，清空交易方式和见证环节的值
            this.rightsForm.tradeType = "";
            this.rightsForm.witnessLink = [];
          }
        } else {
          this.selectedFirstLevelIndustry = val[0][0]; // 记录一下最新选择的行业类别的一级菜单
        }
        // 依据条件禁用“交易方式”的下拉选项
        // for (let i = 0; i < this.tradeTypesOptionsObj[this.rightsForm.industryType[0][0]].length; i++) {
        //   const ei = this.tradeTypesOptionsObj[this.rightsForm.industryType[0][0]][i];
        //   this.$set(ei, "disabled", false);
        //   for (let j = 0; j < this.rightsForm.industryType.length; j++) {
        //     const ej = this.rightsForm.industryType[j];
        //     if (
        //       this.alreadySetTradeTypeObj.hasOwnProperty(ej[0]) &&
        //       this.alreadySetTradeTypeObj[ej[0]].hasOwnProperty(ej[1])
        //     ) {
        //       for (let k = 0; k < this.alreadySetTradeTypeObj[ej[0]][ej[1]].length; k++) {
        //         const ek = this.alreadySetTradeTypeObj[ej[0]][ej[1]][k];
        //         if (ek === ei.value) {
        //           this.$set(ei, "disabled", true);
        //           // 判断选择的交易方式是否被禁用了，若是，清空值
        //           if (this.rightsForm.tradeType === ei.value) {
        //             this.rightsForm.tradeType = "";
        //           }
        //         }
        //       }
        //     }
        //   }
        // }
      },
      changeWitnessLinkFn(e) {
        console.log("e", e);
        console.log("witnessLink", this.witnessLink);
        // this.rightsForm.witnessLink;
        // 根据下拉菜单排序
        const linkArr = [];
        this.witnessLink.forEach((item) => {
          if (e.some((itemB) => itemB === item.value)) {
            linkArr.push(item.value);
          }
        });
        console.log("linkArr", linkArr);
        this.rightsForm.witnessLink = linkArr;
      },
      // 保存用户权限
      saveUserRights() {
        this.submitLoading = true;
        this.$refs["rightsForm"].validate((valid) => {
          if (valid) {
            // 新增
            if (this.rightsDialogType === "new") {
              if (this.rightsRole === "jzy") {
                this.userRightsAdd(this.userForm.jzyRights, this.rightsForm);
              } else {
                this.userRightsAdd(this.userForm.jzglyRights, this.rightsForm);
              }
            }
            // 编辑
            if (this.rightsDialogType === "edit") {
              if (this.rightsRole === "jzy") {
                this.userRightsUpdate(this.userForm.jzyRights, this.rightsForm);
              } else {
                this.userRightsUpdate(this.userForm.jzglyRights, this.rightsForm);
              }
            }
            this.rightsDialogShow = false;
            this.$message({
              type: "success",
              message: this.rightsDialogType === "new" ? "新增成功" : "编辑成功",
              single: true
            });
          }
        });
        setTimeout(() => {
          this.submitLoading = false;
        }, 1005);
      },
      // 用户权限新增
      userRightsAdd(oriArr, form) {
        const children = [];
        for (let i = 0; i < form.industryType.length; i++) {
          const obj = {};
          obj.firstLevelIndustry = form.industryType[i][0]; // 一级行业
          obj.secondLevelIndustry = form.industryType[i][1]; // 二级行业
          obj.tradeType = form.tradeType; // 交易方式
          if (form.witnessLink && form.witnessLink.length > 0) {
            obj.witnessLink = form.witnessLink;
          }
          children.push(obj);
        }
        // 判断一下原来表格中有没有包含当前新增的大行业，若有将当前的children合并上去，若没有，则新增一个数据项
        let contentflag = false; // 是否包含大行业的标志，默认不包含
        for (let i = 0; i < oriArr.length; i++) {
          if (oriArr[i].firstLevelIndustry === form.industryType[0][0]) {
            contentflag = true;
            // 拼接数组
            oriArr[i].children = oriArr[i].children.concat(children);
            break;
          }
        }
        if (!contentflag) {
          const obj = {
            firstLevelIndustry: form.industryType[0][0], // 一级行业
            children: children // 嵌套表格中使用的值
          };
          oriArr.push(obj);
        }
        console.log("oriArr", oriArr);
      },
      // 用户权限更新
      userRightsUpdate(oriArr, form) {
        for (let i = 0; i < oriArr.length; i++) {
          if (oriArr[i].firstLevelIndustry === form.industryType[0][0]) {
            oriArr[i].children[form.index].witnessLink = form.witnessLink;
          }
        }
      },
      // 弹窗取消，表单重置
      cancel() {
        this.rightsDialogShow = false;
        this.$refs.rightsForm.clearValidate();
      },
      // 编辑见证员二级行业权限
      editJzyRights(item, index, role = "jzy") {
        this.rightsRole = role;
        this.rightsDialogTitle = "编辑";
        this.witnessLinkOptionsObj = {};
        this.tenderModeOptionsArr = this.tenderModes; // 编辑需要初始化一次值
        console.log("item", item);
        // 您当前已没有此业务权限，请先确认该见证人已无此权限的业务，以免对已有业务造成影响，明确后可进行删除相应权限操作
        // const links = this.witnessLinksOptionsObj[`${item.firstLevelIndustry}-${item.tradeType}`] || [];
        let links = [];
        const currWitnessLink = [];
        this.industryTypeOptions.forEach((itemA) => {
          console.log("itemA", itemA);
          if (itemA.value === item.firstLevelIndustry) {
            itemA.children.forEach((itemB) => {
              console.log("itemB", itemB);
              if (itemB.value === item.secondLevelIndustry) {
                itemB.childrenIndustry.forEach((itemC) => {
                  console.log("itemC", itemC);
                  if (itemC.value === item.tradeType) {
                    links = itemC.children;
                  }
                });
              }
            });
          }
        });
        // 针对老数据过滤
        links.forEach((itemA) => {
          if (item.witnessLink) {
            const flag = item.witnessLink.some((itemB) => itemB === itemA.value);
            if (flag) {
              currWitnessLink.push(itemA.value);
            }
          }
        });
        this.rightsForm = {
          index: index,
          industryType: [[item.firstLevelIndustry, item.secondLevelIndustry]],
          tradeType: item.tradeType,
          witnessLink: currWitnessLink
        };
        this.selectedFirstLevelIndustry = item.firstLevelIndustry;
        console.log("this.rightsForm", this.rightsForm);
        console.log("this.industryTypeOptions", this.industryTypeOptions);
        let industryFlag = true;
        let tradeTypeFlag = true;
        let witnessLinkFlag = true;
        this.industryTypeOptions.forEach((itemA) => {
          if (itemA.value === item.firstLevelIndustry) {
            itemA.children.forEach((itemB) => {
              console.log("secondLevelIndustry", item.secondLevelIndustry);
              console.log("itemB", itemB);
              if (itemB.value === item.secondLevelIndustry) {
                industryFlag = false;
                itemB.childrenIndustry.forEach((itemC) => {
                  // console.log("itemB", itemB);
                  console.log("itemC==", itemC.value);
                  console.log("tradeType", item.tradeType);
                  if (itemC.value === item.tradeType) {
                    tradeTypeFlag = false;
                    itemC.children.forEach((itemD) => {
                      witnessLinkFlag = false;
                      this.witnessLinkOptionsObj[itemD.value] = itemD.label;
                    });
                  }
                });
              }
            });
          }
        });
        // 行业、交易方式都不能
        // console.log("this.witnessLinkOptionsObj", this.witnessLinkOptionsObj);
        // console.log("industryFlag", industryFlag);
        // console.log("tradeTypeFlag", tradeTypeFlag);
        // console.log("witnessLinkFlag", witnessLinkFlag);
        if (industryFlag || tradeTypeFlag || witnessLinkFlag) {
          this.$message({
            type: "error",
            message:
              "您当前已没有此业务权限，请先确认该见证人已无此权限的业务，以免对已有业务造成影响，明确后可进行删除相应权限操作",
            single: true
          });
          return;
        }
        this.rightsDialogType = "edit";
        this.rightsDialogShow = true;
        // console.log("this.rightsDialogType", this.rightsDialogType);
        // this.witnessLink.forEach((itemD) => {
        //   this.witnessLinkOptionsObj[itemD.value] = itemD.label;
        // });
      },
      // 删除用户权限，item:删除项，index:索引，role:角色，level: 删除层级（first：删除一级行业，second: 删除二级行业）
      delRights(item, index, role, level, mIndex) {
        let str = "";
        // role === "jzy"
        //   ? level === "first"
        //     ? `所有${this.firstLevelIndustrysObj[item.firstLevelIndustry]}类见证权限？`
        //     : "当前见证权限？"
        //   : level === "first"
        //   ? `所有${this.firstLevelIndustrysObj[item.firstLevelIndustry]}类管理权限？`
        //     : "当前见证管理权限？";
        if (role === "jzy") {
          if (level === "first") {
            str = `所有${this.firstLevelIndustrysObj[item.firstLevelIndustry]}类见证权限？`;
          } else {
            str = "当前见证权限？";
          }
        } else if (level === "first") {
          str = `所有${this.firstLevelIndustrysObj[item.firstLevelIndustry]}类管理权限？`;
        } else {
          str = "当前见证管理权限？";
        }
        const tip = `是否确认删除${str}`;
        this.$confirm(tip, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            // 1. 删除见证员权限
            if (role === "jzy") {
              // 判断是否是一级行业的删除
              if (level === "first") {
                this.userForm.jzyRights.splice(index, 1);
              } else {
                const cIndex = this.userForm.jzyRights.findIndex(
                  (cItem) => cItem.firstLevelIndustry === item.firstLevelIndustry
                );
                this.userForm.jzyRights[cIndex].children.splice(index, 1);
              }
            }
            // 2. 删除见证管理员权限
            if (role === "jzgly") {
              // 判断是否是一级行业的删除
              if (level === "first") {
                this.userForm.jzglyRights.splice(index, 1);
              } else {
                // let cIndex = this.userForm.jzyRights.findIndex(cItem => cItem.firstLevelIndustry === item.firstLevelIndustry);
                // this.userForm.jzglyRights[cIndex].children.splice(index, 1);
                this.userForm.jzglyRights[mIndex].children.splice(index, 1);
              }
            }
            this.$message({
              type: "success",
              message: "删除成功",
              single: true
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
              single: true
            });
          });
      },
      // 行业格式化内容
      secondLevelIndustryFormatter(row, column, cellValue) {
        console.log("cellValue", cellValue);
        if (cellValue) {
          // this.industryAll 这里接口可能会变 by link
          const o = this.industryAll.find((item) => item.value === cellValue);
          return o.label;
        }
        return "";
      },
      // 见证环节格式化内容
      tradTypeFormatter(row, column, cellValue) {
        console.log("cellValue", cellValue);
        if (cellValue) {
          const o = this.tenderModes.find((item) => item.value === cellValue);
          return o.label;
        }
        return "";
      },
      // 见证环节格式化内容
      witnessLinkFormatter(row, column, cellValue) {
        // console.log("row", row);
        if (cellValue) {
          const newArr = [];
          // console.log("this.witnessLink", this.witnessLink);
          // console.log("cellValue", cellValue);
          for (let i = 0; i < cellValue.length; i++) {
            const a = this.witnessLink.find(
              (item) =>
                // console.log(item.value, cellValue[i]);
                // console.log(item.value === cellValue[i]);
                item.value === cellValue[i]
            );
            // console.log("a", a);
            newArr.push(a.label);
            // 这个废弃
            // newArr.push(this.witnessLinksObj[row.firstLevelIndustry + "-" + row.tradeType][cellValue[i]]);
          }
          return newArr.join("；");
        }
        return "";
      },
      // 保存用户信息
      saveUserInfo(form) {
        this.$refs["userForm"].validate((valid) => {
          if (valid) {
            // 判断是否通过权限配置的验证
            if (
              !this.validateRightsList(form.jzyRights, form.userRoles.indexOf("GDW_R_WITNESS_PERSON") > -1) ||
              !this.validateRightsList(form.jzglyRights, form.userRoles.indexOf("GDW_R_WITNESS_MANAGER") > -1)
            ) {
              return;
            }
            // 见证人员权限
            let jzyListReq = [];
            if (form.userRoles.indexOf("GDW_R_WITNESS_PERSON") > -1) {
              jzyListReq = this.getPermissionListReq(form.jzyRights, "jzy");
            }
            // 见证管理员权限
            let jzglyListReq = [];
            if (form.userRoles.indexOf("GDW_R_WITNESS_MANAGER") > -1) {
              jzglyListReq = this.getPermissionListReq(form.jzglyRights, "jzgly");
            }
            const params = {
              loginName: form.loginName,
              password: form.password,
              userName: form.userName,
              userIdCard: form.userIdCard,
              userTel: form.userTel,
              userStatus: form.userStatus,
              generalPermissionListReq: jzyListReq,
              managerPermissionListReq: jzglyListReq
            };
            // 新增
            if (this.operationType === "new") {
              this.userAddFn(params);
            }
            // 更新
            if (this.operationType === "edit") {
              params.witnessUserId = this.witnessUserId;
              this.userUpdateFn(params);
            }
          } else {
            this.$message({
              type: "warning",
              message: "请仔细检查表单，填写必填项",
              single: true
            });
          }
        });
      },
      // 权限配置的验证，arr:行业数组，roleSelected:是否选择了该行业的对应角色
      validateRightsList(arr, roleSelected) {
        /* 验证逻辑：
        1. 若是选择了对应角色，却没有配置权限，不通过
        2. 若是配置的某个一级行业下面没有二级行业，不通过
      */
        let flag = true; // 默认通过验证
        if (roleSelected && arr.length === 0) {
          flag = false;
        } else {
          for (let i = 0; i < arr.length; i++) {
            if (!arr[i].children || arr[i].children.length === 0) {
              flag = false;
              break;
            }
          }
        }
        if (!flag) {
          this.$message({
            type: "error",
            message: "请先完成用户角色权限配置，再进行保存",
            single: true
          });
        }
        return flag;
      },
      // 生成后端需要的权限列表
      getPermissionListReq(oriArr, role) {
        const newArr = [];
        for (let i = 0; i < oriArr.length; i++) {
          if (oriArr[i].children) {
            for (let j = 0; j < oriArr[i].children.length; j++) {
              const e = oriArr[i].children[j];
              // if (role === "jzy") {
              // 见证员有见证环节
              for (let k = 0; k < e.witnessLink.length; k++) {
                const obj = {
                  industryType: e.firstLevelIndustry,
                  industry: e.secondLevelIndustry,
                  tenderMode: e.tradeType,
                  witnessLinkNum: parseInt(e.witnessLink[k])
                };
                newArr.push(obj);
              }
              // } else {
              //   const obj = {
              //     industryType: e.firstLevelIndustry,
              //     industry: e.secondLevelIndustry,
              //     tenderMode: e.tradeType
              //   };
              //   newArr.push(obj);
              // }
            }
          }
        }
        return newArr;
      },
      // 见证用户管理新增接口
      async userAddFn(params) {
        try {
          this.saveLoading = true;
          const res = await userAdd(params);
          this.saveLoading = false;
          if (res.success) {
            this.haveSaved = true;
            this.$message({
              type: "success",
              message: "保存成功",
              single: true,
              onClose: () => {
                this.$emit("close");
              }
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "保存失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.log(error);
          this.saveLoading = false;
        }
      },
      // 见证用户管理修改接口
      async userUpdateFn(params) {
        try {
          this.saveLoading = true;
          const res = await userUpdate(params);
          this.saveLoading = false;
          if (res.success) {
            this.haveSaved = true;
            this.$message({
              type: "success",
              message: "保存成功",
              single: true,
              onClose: () => {
                this.$emit("close");
              }
            });
          } else {
            this.$message({
              type: "error",
              message: res.message || "保存失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.log(error);
          this.saveLoading = false;
        }
      },
      goBack() {
        this.$emit("close");
      },
      // 查看见证人员信息接口
      async userDetailFn(witnessUserId) {
        try {
          this.pageLoading = true;
          const res = await userDetail({ witnessUserId });
          this.pageLoading = false;
          if (res.success) {
            const userRoles = Object.keys(res.data.userPermission);
            let jzyRights = [];
            if (userRoles.indexOf("GDW_R_WITNESS_PERSON") > -1) {
              jzyRights = this.getFormRights(res.data.userPermission.GDW_R_WITNESS_PERSON, "jzy");
            }
            let jzglyRights = [];
            if (userRoles.indexOf("GDW_R_WITNESS_MANAGER") > -1) {
              jzglyRights = this.getFormRights(res.data.userPermission.GDW_R_WITNESS_MANAGER, "jzgly");
            }
            this.userForm = {
              userCode: res.data.userCode,
              userName: res.data.userName,
              userIdCard: res.data.userIdCard,
              userTel: res.data.userTel,
              userStatus: res.data.userStatusEnum,
              loginName: res.data.loginName,
              password: res.data.password,
              userRoles: userRoles,
              jzyRights: jzyRights,
              jzglyRights: jzglyRights
            };
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.log(error);
          this.pageLoading = false;
        }
      },
      // 将后端接口返回的权限数据重构为页面显示的数据结构
      getFormRights(oriArr, role) {
        const newArr = [];
        // 若是见证管理员角色，需要将一级行业相同的进行归类
        // if (role === "jzgly") {
        //   for (let i = 0; i < oriArr.length; i++) {
        //     const objIn = {
        //       firstLevelIndustry: oriArr[i].industryType,
        //       secondLevelIndustry: oriArr[i].industry,
        //       tradeType: oriArr[i].tenderMode
        //     };
        //     const objOut = newArr.find((item) => item.firstLevelIndustry === oriArr[i].industryType);
        //     if (objOut) {
        //       objOut.children.push(objIn);
        //     } else {
        //       newArr.push({
        //         firstLevelIndustry: oriArr[i].industryType,
        //         children: [objIn]
        //       });
        //     }
        //   }
        // }
        // 若是见证员角色，在按照一级行业分类的基础上，还要将二级行业和交易方式相同的进行归类
        // if (role === "jzy") {
        for (let i = 0; i < oriArr.length; i++) {
          const objIn = {
            firstLevelIndustry: oriArr[i].industryType,
            secondLevelIndustry: oriArr[i].industry,
            tradeType: oriArr[i].tenderMode
          };
          // 判断有没有相同的一级行业
          const objOut = newArr.find((item) => item.firstLevelIndustry === oriArr[i].industryType);
          if (objOut) {
            // 判断有没有相同的一级行业、二级行业、交易方式
            const index = objOut.children.findIndex(
              (item) =>
                item.firstLevelIndustry === oriArr[i].industryType &&
                item.secondLevelIndustry === oriArr[i].industry &&
                item.tradeType === oriArr[i].tenderMode
            );
            if (index > -1) {
              objOut.children[index].witnessLink.push(oriArr[i].witnessLinkNum.toString());
            } else {
              console.log("oriArr[i].witnessLinkNum", oriArr[i].witnessLinkNum);
              if (oriArr[i].witnessLinkNum) {
                objIn.witnessLink = [oriArr[i].witnessLinkNum.toString()];
              } else {
                objIn.witnessLink = [];
              }
              objOut.children.push(objIn);
            }
          } else {
            console.log("oriArr[i].witnessLinkNum", oriArr[i].witnessLinkNum);
            if (oriArr[i].witnessLinkNum) {
              objIn.witnessLink = [oriArr[i].witnessLinkNum.toString()];
            } else {
              objIn.witnessLink = [];
            }
            newArr.push({
              firstLevelIndustry: oriArr[i].industryType,
              children: [objIn]
            });
          }
        }
        // }
        return newArr;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .user-info-body {
    width: 100%;
    flex-direction: column;
    overflow: auto;
  }
  .user-info-footer {
    padding: 10px;
    text-align: right;
    border-top: 1px solid #d2d2d2;
  }
</style>
<style lang="scss">
  .user-info-page {
    .el-collapse.is-card .el-collapse-item {
      box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
      border-radius: 2px;
    }
  }
  .select-border-circle .el-cascader-panel > :first-child {
    .el-checkbox__inner {
      border-radius: 50%;
    }
  }
  // 修改嵌套表格样式
  .el-table--card > .el-table__header-wrapper th:first-child {
    border-left: none !important;
  }
  .el-table--card.el-table td.el-table__expanded-cell {
    padding: 0 !important;
    margin-top: 0 !important;
    margin-bottom: 10px !important;
  }
  .el-table--card {
    .el-scrollbar__bar {
      position: unset !important;
    }
    .el-table__header {
      border-right: none;
      th {
        border-top: none !important;
        font-weight: bold;
      }
    }
    .table-in-table {
      top: -10px;
      table {
        border-spacing: 0px !important;
        // border-top: 1px solid red;
        border-top: none;
        tr {
          border-spacing: 0px !important;
          td,
          th {
            background: #e5e5e5 !important;
            border-spacing: 0px !important;
            // border-left: 1px solid #fff !important;
          }
          td {
            background: #fff !important;
            margin-bottom: 10px !important;
            border-top: none !important;
            border-color: #d2d2d2 !important;
          }
          td:first-child {
            border-left: 1px solid #d2d2d2 !important;
          }
        }
        .hover_row {
          border: none;
        }
      }
    }
  }
  .el-table--card .el-table__body-wrapper .el-table__row td:first-child .cell::before,
  .el-table--card .el-table__fixed-body-wrapper .el-table__row td:first-child .cell::before {
    display: none;
  }
</style>
